package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//定义拦截器
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取请求头token
        String token = request.getHeader("Authorization");
        //2.校验token合法性
        boolean verifyToken = JwtUtils.verifyToken(token);
        if(!verifyToken){
            //token为空或失效
            response.setStatus(401);
            return false;
        }

        //3.token正常,获取token携带的用户id和手机号码构造用户存进threadlocal
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");
        String phone = (String) claims.get("phone");

        User user =new User();
        user.setId(Long.valueOf(id));
        user.setMobile(phone);

        ThreadLocalUtils.set(user);

        return true;
    }

    //线程结束之后清空ThreadLocal中的数据
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtils.remove();
    }
}
